package ss12.MobileColorIdentifier.database;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.InputStream;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBase {

	public static final String KEY_CODE = "hex";
	public static final String KEY_NAME = "name";
	public static final String KEY_ROWID = "_id";

	private static final String TAG = "IdentifierDb";
	private DatabaseHelper mDbHelper;
	private static SQLiteDatabase mDb;

	private static final String DATABASE_CREATE =
		"create table hexToColor (_id integer primary key autoincrement, "
		+ "hex text not null, name text not null);";

	private static final String DATABASE_NAME = "CMap";
	private static final String DATABASE_TABLE = "hexToColor";
	private static final int DATABASE_VERSION = 2;

	private static Context mCtx;

	private static class DatabaseHelper extends SQLiteOpenHelper {
		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
			//populate the DB
			populateDb();
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS notes");
			onCreate(db);
		}
	}

	public DataBase(Context ctx) {
		this.mCtx = ctx;
	}

	public DataBase open() throws SQLException {
		mDbHelper = new DatabaseHelper(mCtx);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		mDbHelper.close();
	}

	public static long createNote(String hex, String name) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_CODE, hex);
		initialValues.put(KEY_NAME, name);
		return mDb.insert(DATABASE_TABLE, null, initialValues);
	}

	public boolean deleteNote(long rowId) {
		return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}

	public Cursor fetchAllNotes() {
		return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_CODE,
				KEY_NAME}, null, null, null, null, null);
	}

	public Cursor fetchNote(long rowId) throws SQLException {
		Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
				KEY_CODE, KEY_NAME}, KEY_ROWID + "=" + rowId, null,
				null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}


	public Cursor fetchNoteTitle(String search) throws SQLException {
		Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
				KEY_CODE, KEY_NAME}, KEY_CODE + "=" + search, null,
				null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}

	public Cursor fetchNoteCode(String search) throws SQLException {
		Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
				KEY_CODE, KEY_NAME}, KEY_CODE + " like " + "'%"+search+"%'", null,
				null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}

	public boolean updateNote(long rowId, String code, String name, String lat, String longi, String desc) {
		ContentValues args = new ContentValues();
		args.put(KEY_CODE, code);
		args.put(KEY_NAME, name);
		return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
	}

	//populate the Db
	public static void populateDb()
	{
		//File file = new File("/data/data/assets/color_codes.txt");
		if(mDb == null){
			new DataBase(mCtx).open();			
		}
		
		try {
			InputStream in = mCtx.getAssets().open("color_codes.txt");
			BufferedInputStream bin = new BufferedInputStream(in);
			DataInputStream din = new DataInputStream(bin);
			
			//read and discard the first line 
			din.readLine();

			//parse the file
			while (din.available() != 0) {
				String tok1 = din.readLine();

				//if not the last line
				if(tok1.length()!= 1) {
					final int startIndex1 = 2;
					final int startIndex2 = 13;
					final int endIndex1 = 7;
					final int endIndex2 = tok1.length()-3;
					
					String str1 = tok1.substring(startIndex1,endIndex1);
					String str2 = tok1.substring(startIndex2,endIndex2);
					createNote(str1,str2);
				}
			}

			//close all the files
			in.close();
			bin.close();
			din.close();

			if(mDb != null){
				new DataBase(mCtx).close();
			}
			
		} catch (Exception e) {
			if(mDb != null){
				new DataBase(mCtx).close();
			}
			e.printStackTrace();
		}
	}
}
